package com.hrm.controller;

import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSON;
import com.hrm.entity.Dept;
import com.hrm.entity.Employee;
import com.hrm.entity.Job;
import com.hrm.entity.User;
import com.hrm.module.Dto;
import com.hrm.service.lxy.EmpService;
import com.hrm.utils.BaseCryptographyUtils;
import com.hrm.utils.Constants;
import com.hrm.utils.DtoUtil;
import com.hrm.utils.PageInfo;
import org.apache.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 员工管理
 *
 * @author 李雪阳
 * @version 1.0
 * @date 2020/8/1 17:01
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmpService empService;
    Logger logger = Logger.getLogger(EmployeeController.class);
    //从类路径中加载文件
    private static Properties properties = null;
    private static String aesKey = "chongcibchongcibchongcibchongcib";
    private static String desKey = "chongcibchongcibchongcibchongcibchongcibchongcibchongcibchongcib";

    static {
        try {
            properties = PropertiesLoaderUtils.loadAllProperties("key.properties");
            aesKey = properties.getProperty("aeskey");
            desKey = properties.getProperty("deskey");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 查看员工列表，支持模糊查询+分页功能
     *
     * @param name
     * @param pageNo
     * @param request
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String getEmpList(@RequestParam(required = false) String name,
                             @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                             HttpServletRequest request, HttpSession session, Model model) {
        //员工总记录数
        int totalRows = empService.getEmpNum(name);
        PageInfo<Employee> page = new PageInfo<>();
        page.setTotalRows(totalRows);
        int[] rainbow = null;
        List<Employee> empList = null;
        if (totalRows != 0) {
            page.setPageNo(pageNo);
            Integer totalPages = page.getTotalPages();
            //彩虹分页
            rainbow = PageUtil.rainbow(pageNo, totalPages, 5);
            logger.info("TotalPages：" + totalPages);
            empList = empService.getEmpList(name, page);
            logger.info(JSON.toJSONString(empList));
        } else {
            page.setPageNo(0);
        }
        request.setAttribute("list", empList);
        request.setAttribute("name", name);
        model.addAttribute("page", page);
        model.addAttribute("rainbow", rainbow);
        return "employee/list";
    }

    /**
     * 进入新增或者修改页面，它两是同一个页面
     *
     * @param id
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/add")
    public String toAdd(@RequestParam(required = false) Integer id,
                        HttpServletRequest request, Model model) {
        Employee empById = null;
        if (id != null) {
            empById = empService.getEmpById(id);
            if (empById != null) {
                //解密
                String pass = BaseCryptographyUtils.desDecodeHexString(empById.getPassword(), desKey);
                empById.setPassword(pass);
                model.addAttribute(empById);
            }
        }
        logger.info(JSON.toJSONString(empById));
        List<Dept> deptList = empService.getDeptList();
        logger.info(JSON.toJSONString(deptList));
        List<Job> jobList = empService.getJobList();
        logger.info(JSON.toJSONString(jobList));
        request.setAttribute("dept_list", deptList);
        request.setAttribute("job_list", jobList);
        return "employee/add";
    }

    /**
     * 新增+修改的提交
     * 如果是表单提交的对象，参数前面不能加@RequestParam。
     *
     * @param emp
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Dto<T> addEmp(Employee emp, @RequestParam Integer id,
                         HttpSession session) {
        //密码加密存储
        String password = emp.getPassword();
        password = BaseCryptographyUtils.desEncodeHexString(password, desKey);
        emp.setPassword(password);
        if (id == null) {
            User user = (User) session.getAttribute(Constants.USER_SESSION);
            if (user != null) {
                //存入创建人id
                emp.setCuid(user.getId());
            }
            int count = empService.addEmp(emp);
            if (count > 0) {
                return DtoUtil.returnSuccess();
            } else {
                return DtoUtil.returnFail();
            }
        } else {
            int count = empService.updateEmpById(emp);
            if (count > 0) {
                return DtoUtil.returnSuccess();
            } else {
                return DtoUtil.returnFail();
            }
        }
    }

    /**
     * 根据员工id删除
     *
     * @param id
     */
    @GetMapping("delete")
    public void removeEmp(@RequestParam Integer id) {
        int count = empService.deleteEmpById(id);
        logger.info(count);
    }

}
